/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DataModels;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TOSHIBA
 */
public class FileOp{
    
 public final ArrayList<RestaurantUser> allUsers = new ArrayList<RestaurantUser>();
    public ArrayList<RestaurantUser> readFromFile() {
        try {
                FileInputStream fis = new FileInputStream("C:\\Users\\TOSHIBA\\Desktop\\RestaurantDB.txt");
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                
                String line = "";
                ArrayList<RestaurantUser> myUsers = new ArrayList<RestaurantUser>();
                
                
                while((line = br.readLine()) != null)
                {
                    myUsers.add(getUserFromLine(line));
                }
                br.close();
                return myUsers;
                
        } catch (Exception ex) {
            Logger.getLogger(FileOp.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        
    }
    
    private RestaurantUser getUserFromLine(String line)
    {
        RestaurantUser myUser = new RestaurantUser();
        
        String[] userData = line.split("#");
        myUser.setUsername(userData[0]);
        myUser.setPassword(userData[1]);
        
        
        return myUser;
    }

    public boolean writeToFile(String userData)
    {
        try
        {
            FileOutputStream fos = new FileOutputStream("C:\\Users\\TOSHIBA\\Desktop\\RestaurantDB.txt",true);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            PrintWriter pw = new PrintWriter(osw);

            pw.println(userData);
            pw.flush();
            pw.close();
        
            return true;
        
        }
        catch(Exception e)
        {
            System.out.println("Can't write to the located file");
            return false;
        }
    }


}
